package com.xh.bussiness.permission.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.xh.bussiness.permission.bean.request.MenuRequest;
import com.xh.bussiness.permission.service.IMenuService;
import com.xh.bussiness.permission.service.IUserRoleService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "菜单接口")
@RestController
@RequestMapping("/permission/menu")
public class MenuController extends BaseController {

    @Autowired
    private IMenuService menuService;
    @Autowired
    private IUserRoleService userRoleService;

    @ApiOperation(value = "菜单查询",notes = "菜单查询")
    @PostMapping("/queryAll")
    public AjaxResult queryAll(MenuRequest bean){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", menuService.queryMenu(bean));
    }


    @ApiOperation(value = "菜单分页查询",notes = "菜单分页查询")
    @PostMapping("/queryPage")
    public AjaxResult queryPage(XhPage page, MenuRequest bean){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "",  menuService.queryMenuPage(page,bean));
    }


    @ApiOperation(value="新增菜单",notes = "新增菜单")
    @PostMapping(value="/add")
    @Transactional
    public AjaxResult add(MenuRequest bean){
        String msg=menuService.addMenu(bean);
        return new AjaxResult(msg==null,msg);
    }


    @ApiOperation(value="修改菜单",notes = "修改菜单")
    @PostMapping(value="/modify")
    @Transactional
    public AjaxResult modify(MenuRequest bean){
        String msg=menuService.modifyMenu(bean);
        return new AjaxResult(msg==null,msg);
    }


    @ApiOperation(value = "删除菜单",notes = "删除菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "菜单id",required = true,dataType = "String")
    })
    @PostMapping("/delete")
    @Transactional
    public AjaxResult delete(String id){
        String msg=menuService.deleteMenu(id);
        return new AjaxResult(msg==null,msg);
    }

    @RequestMapping("/queryAllMenuTree")
    public AjaxResult queryAllMenuTree() {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, menuService.queryMenuTree());
    }

    @ApiOperation(value = "根据用户查找菜单",notes = "根据用户查找菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "根据用户查找菜单",required = true,dataType = "String")
    })
    @GetMapping("/queryMenuByUserId")
    public AjaxResult queryMenuByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        List<Map<String, Object>> menuFunctions = userRoleService.queryMenuFunctionsByUserId(userId);
        Map<String, Map<String, Object>> permisstions = new HashMap<>();
        if (menuFunctions != null) {
            for (Map<String, Object> item : menuFunctions) {
                String url = (String) item.get("url");
                String userFunctions = (String) item.get("user_functions");
                userFunctions = StringUtils.isEmpty(userFunctions) ? "" : userFunctions.trim();
                item.replace("user_functions", userFunctions);
                if (!StringUtils.isEmpty(url)) {
                    permisstions.put(url, item);
                }
            }
        }
        //处理菜单树
        JSONArray menusTree = new JSONArray();
        Predicate<Map<String, Object>> predicate = new Predicate<Map<String, Object>>() {
            @Override
            public boolean apply(Map<String, Object> input) {
                return StringUtils.isEmpty((String) input.get("parent_id"));
            }
        };
        Collection<Map<String, Object>> rootList = Collections2.filter(menuFunctions, predicate);
        rootList.stream().forEach(item -> {
            JSONObject node = (JSONObject) JSONObject.toJSON(item);
            node = findChild(node, menuFunctions);
            menusTree.add(node);
        });
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, menusTree);
    }

    /**
     * 菜单list转树状结构递归
     *
     * @param node
     * @param list
     * @return
     */
    private JSONObject findChild(JSONObject node, List<Map<String, Object>> list) {
        JSONArray childs = new JSONArray();
        for (Map<String, Object> item : list) {
            if (node.getString("id").equals((String) item.get("parent_id"))) {
                JSONObject child = (JSONObject) JSONObject.toJSON(item);
                childs.add(findChild(child, list));
            }
        }
        node.put("childs", childs);
        return node;
    }

}

